package com.leandom.studydemo.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.util.Log;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class StorageActivity extends AppCompatActivity {

    private static final String TAG = "StorageActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        testStorage();
    }

    // reference: https://blog.csdn.net/yus201120/article/details/100581951
    private void testStorage() {
        StorageManager mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
            return;
        }
        List<StorageVolume> volumeList = mStorageManager.getStorageVolumes();
        Log.d(TAG, "getStorageVolumes: " + volumeList.size());
        for (StorageVolume volume : volumeList) {
            String label = volume.getDescription(this);          //这个其实就是U盘的名称
            String status = volume.getState();                   //设备挂载的状态，如:mounted、unmounted
            boolean isEmulated = volume.isEmulated();            //是否是内部存储设备
            boolean isRemovable = volume.isRemovable();          //是否是可移除的外部存储设备
            String path = "";                                   //设备的路径

            try {
                Class myclass = Class.forName(volume.getClass().getName());
                Method getPath = myclass.getDeclaredMethod("getPath", null);
                getPath.setAccessible(true);
                path = (String) getPath.invoke(volume);

                Log.i(TAG, "name:" + label);
                Log.i(TAG, "status:" + status);
                Log.i(TAG, "isEmulated:" + isEmulated);
                Log.i(TAG, "isRemovable:" + isRemovable);
                Log.i(TAG, "path:" + path);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
